<template>
  <div class="page luckdraw-add">
    <div class="luckdraw-add-container">
      <div class="banner-section">
        <img :src="selectedImage ? selectedImage : icons[0]" mode="aspectFill"/>
        <a @click="onChangeImageClick">更改奖品图片</a>
      </div>
      <m-input
        title="奖品名称"
        placeholder="请输入奖品名称"
        v-model="awardName">
      </m-input>
      <m-input
        type="number"
        title="奖品数量"
        placeholder="请输入奖品数量（个）"
        v-model="awardNumber">
      </m-input>
      <m-link
        title="开奖条件"
        :addon="conditionList[conditionIndex]"
        @on-click="onAwardConditionLinkClick">
      </m-link>
      <m-input
        v-if="conditionIndex === 1"
        type="number"
        title="开奖人数"
        placeholder="请输入开奖人数（人）"
        v-model="awardMember"
        :isLast="true">
      </m-input>
      <m-link
        v-if="conditionIndex === 0"
        title="开奖时间"
        :addon="awardTime"
        isLast
        @on-click="onAwardTimeLinkClick">
      </m-link>
      <picker-view
        v-if="showTimePicker"
        class="award-time-picker"
        indicator-style="height:35px; background-color: transparent; border: none;"
        @change="bindTimePickerChange"
        :value="timePickerValue">
        <picker-view-column class="award-time-column1">
          <div v-for="(item, i) in rangeArr[0]" :key="i" class="award-time-item">{{item}}</div>
        </picker-view-column>
        <picker-view-column class="award-time-column2">
          <div v-for="(item, i) in rangeArr[1]" :key="i" class="award-time-item">{{item}}</div>
        </picker-view-column>
        <picker-view-column class="award-time-column3">
          <div v-for="(item, i) in rangeArr[2]" :key="i" class="award-time-item">{{item}}</div>
        </picker-view-column>
      </picker-view>
      <div class="award-supplement-option">
        <p>补充说明</p>
        <switch @change="switchChange" color="#448ff0"/>
      </div>
      <div class="award-supplement" v-if="showAwardSupplement">
        <m-input
          title="微信号"
          placeholder="请输入微信号（选填）"
          isLast
          v-model="wechatName">
        </m-input>
      </div>
      <div class="to-vip">
        <span @click="onToVipClick">使用高级版 ></span>
      </div>
      <div class="btn-section">
        <div class="btn-inner">
          <m-button text="发起新抽奖" type="red" @onClick="createActivity"></m-button>
        </div>
      </div>
    </div>
    <m-toast v-model="toastContent"></m-toast>
    <pay-dialog :show.sync="showPayDialog" :coin="coinForCreateVip" @onClick="onGoToVip"></pay-dialog>
  </div>
</template>

<script>
import MButton from 'comp/m-button'
import MInput from 'comp/m-input'
import MLink from 'comp/m-link'
import MToast from 'comp/m-toast'
import PayDialog from 'comp/pay-dialog'
import { uploadFile } from '@/utils/wx'
import { apiDomain } from '@/utils/constant'
import mixins from 'comp/mixins'

const weekday = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']

export default {
  mixins: [mixins],
  components: {
    MButton,
    MInput,
    MLink,
    MToast,
    PayDialog
  },
  data () {
    return {
      icons: [
        `${require('static/images/award-bg.png')}`,
      ],
      selectedImage: '',
      uploadImageUrl: '',
      awardName: '',
      awardNumber: '',
      awardTime: '',
      awardMember: '',
      wechatName: '',
      showTimePicker: false,
      rangeArr: [],
      timePickerValue: [],
      conditionList: [
        '按时间自动开奖',
        '按人数自动开奖'
      ],
      conditionLabel: [
        '到达设定时间自动开奖',
        '3天内到达设定人数自动开奖'
      ],
      conditionIndex: 0,
      toastContent: '',
      showAwardSupplement: false,
      showPayDialog: false,
      coinForCreateVip: ''
    }
  },
  mounted () {
    this.resetData()
    this.getDefaultTime()
    this.initRangeArr()
    this.queryConfig()
  },
  methods: {
    /**
     * 更改奖品图片
     */
    onChangeImageClick () {
      wx.chooseImage({
        count: 1,
        sizeType: ['compressed'], // 指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'],
        success: (res) => {
          // 返回选定照片的本地文件路径列表
          this.selectedImage = res.tempFilePaths[0]
        }
      })
    },
    onAwardTimeLinkClick () {
      this.showTimePicker = !this.showTimePicker
    },
    /**
     * 获取默认的开奖时间，未来半小时内
     */
    getDefaultTime () {
      let str
      const date = new Date()
      if (date.getMinutes() < 30) {
        str = `${date.getMonth() + 1}月${date.getDate()}日 ${weekday[date.getDay()]} ${date.getHours()}:30`
        // 初始化的value
        this.timePickerValue = [0, date.getHours(), 1]
      } else {
        date.setHours(date.getHours() + 1)
        str = `${date.getMonth() + 1}月${date.getDate()}日 ${weekday[date.getDay()]} ${date.getHours()}:00`
        // 初始化的value
        this.timePickerValue = [0, date.getHours(), 0]
      }
      this.awardTime = str
    },
    /**
     * 初始化开奖时间选择列表
     */
    initRangeArr () {
      let arr = []

      // 日期和星期，未来一周（1+7天）
      let dateArr = []
      for (let i = 0; i < 8; i++) {
        const date = new Date()
        date.setDate(date.getDate() + i)
        dateArr[i] = `${date.getMonth() + 1}月${date.getDate()}日 ${weekday[date.getDay()]}`
      }

      // 小时
      let hourArr = []
      for (let i = 0; i < 24; i++) {
        hourArr[i] = i
      }

      arr[0] = dateArr
      arr[1] = hourArr
      arr[2] = ['00', '30']

      this.rangeArr = arr
    },
    /**
     * 选中的日期
     */
    bindTimePickerChange (e) {
      const indexArr = e.mp.detail.value
      const rangeArr = this.rangeArr
      this.awardTime = `${rangeArr[0][indexArr[0]]} ${rangeArr[1][indexArr[1]]}:${rangeArr[2][indexArr[2]]}`
      // 保存value，用于下次回显
      this.timePickerValue = indexArr
    },
    /**
     * 修改开奖条件，显示选择面板
     */
    onAwardConditionLinkClick () {
      wx.showActionSheet({
        itemList: this.conditionList,
        success: (res) => {
          this.bindConditionPickerChange(res.tapIndex)
        },
        fail: (res) => {
          console.log(res.errMsg)
        }
      })
    },
    /**
     * 选中开奖条件
     */
    bindConditionPickerChange (i) {
      this.conditionIndex = i
      if (i === 1) {
        this.showTimePicker = false
      }
    },
    /**
     * 创建活动，step1 上传图片（如有图片）
     */
    async createActivity () {
      if (!this.checkForm()) {
        return
      }
      if (this.selectedImage) {
        uploadFile({
          url: `${apiDomain}/api/file/img`,
          filePath: this.selectedImage,
          name: 'file',
          formData: {
            'type': 'luckdraw:award'
          }
        }).then((res) => {
          if (res.statusCode !== 200) {
            wx.showModal({
              title: '提示',
              content: '上传失败',
              showCancel: false
            })
            return false
          }
          const data = JSON.parse(res.data)
          this.uploadImageUrl = data && data.result && data.result.img
          this.submitActivity()
        })
      } else {
        this.submitActivity()
      }
    },
    /**
     * 创建活动，step2 提交活动
     */
    async submitActivity () {
      const openId = await this.getOpenId()
      let postData = {
        createrId: openId,
        awardTitle: this.awardName,
        awardImage: this.uploadImageUrl,
        awardAmount: parseInt(this.awardNumber),
        info: JSON.stringify({
          wechatName: this.wechatName
        })
      }
      if (this.conditionIndex === 0) {
        // 按到时间抽奖
        postData = {
          ...postData,
          type: 1,
          awardTime: this.handleAwardTime()
        }
      } else {
        // 按满人数抽奖
        postData = {
          ...postData,
          type: 2,
          awardPeople: parseInt(this.awardMember)
        }
      }
      const res = await this.$store.dispatch('createActivity', postData)
      if (res.code === 0) {
        wx.navigateTo({
          url: `/pages/add-result/main?activityId=${res.result.activity_id}`
        })
      }
    },
    /**
     * 开奖时间格式化为秒
     */
    handleAwardTime () {
      // 2013/3/8 17:20
      const awardTime = this.awardTime
      const lit = awardTime.split(' ')
      const date = lit[0]
      const time = lit[2]

      const month = date.split('月')[0]
      const day = (date.split('月')[1]).split('日')[0]

      const _date = new Date()
      const year = _date.getFullYear()

      const str = `${year}/${month}/${day} ${time}`
      const output = (new Date(str)).getTime() / 1000

      return output
    },
    /**
     * 表单校验
     */
    checkForm () {
      if (!this.awardName) {
        this.toastContent = '请输入奖品名称'
        return false
      }
      if (!this.awardNumber) {
        this.toastContent = '请输入奖品数量'
        return false
      }
      if (this.conditionIndex === 1) {
        if (!this.awardMember) {
          this.toastContent = '请输入开奖人数'
          return false
        }
        if (parseInt(this.awardMember) < parseInt(this.awardNumber)) {
          this.toastContent = '开奖人数不能小于奖品数量'
          return false
        }
        if (parseInt(this.awardMember) > 1024) {
          this.toastContent = '开奖人数不能大于1024'
          return false
        }
      }
      if (this.conditionIndex === 0) {
        if (!this.awardTime) {
          this.toastContent = '请选择开奖时间'
          return false
        }
        const awardTime = this.handleAwardTime()
        const date = new Date().getTime() / 1000
        if (awardTime <= date) {
          this.toastContent = '开奖时间不能早于当前时间'
          return false
        }
      }
      return true
    },
    /**
     * 补充说明开关
     */
    switchChange (e) {
      if (e.mp.detail.value) {
        this.showAwardSupplement = true
      } else {
        this.showAwardSupplement = false
      }
    },
    /**
     * 使用高级版
     */
    onToVipClick () {
      this.showPayDialog = true
    },
    /**
     * 前往高级版
     */
    onGoToVip () {
      wx.redirectTo({
        url: '/pages/add-vip/main'
      })
    },
    /**
     * 获取高级版金币所用金币配置
     */
    async queryConfig () {
      const ret = await this.$store.dispatch('queryConfig', {
        noToast: true
      })
      this.coinForCreateVip = ret.goldCreatedActivity
    }
  }
}
</script>

<style lang="less" scoped>
.luckdraw-add {
  &-container {
    padding-bottom: 30rpx;
  }
  .banner-section {
    position: relative;
    img {
      display: block;
      width: 100%;
      height: 400rpx;
    }
    a {
      display: block;
      position: absolute;
      top: 14rpx;
      right: 14rpx;
      font-size: 28rpx;
      color: #333;
      text-align: center;
      background-color: #fff;
      border: 1rpx solid #575757;
      padding: 16rpx 20rpx;
      &:active {
        background: #d8d8d8;
      }
    }
  }
  .award-option {
    display: flex;
    justify-content: space-between;
    padding: 40rpx 30rpx 20rpx;
    font-size: 30rpx;
    color: #777;
    a {
      color: #448ff0;
    }
  }
  .award-supplement-option {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 30rpx;
    margin-top: 20rpx;
    font-size: 32rpx;
    color: #333;
    background-color: #fff;
  }
  .award-supplement {
    margin-top: 20rpx;
  }
  .award-time-picker {
    width: 100%;
    height: 360rpx;
    border-top: 1rpx solid #e6ebf0;
    font-size: 30rpx;
    text-align: center;
  }
  .award-time-column1 {
    flex: 2;
  }
  .award-time-column2, .award-time-column3 {
    flex: 1;
  }
  .award-time-item {
    height: 70rpx;
    line-height: 70rpx;
  }
  .award-condition-picker {
    width: 100%;
    height: 240rpx;
    border-top: 1rpx solid #e6ebf0;
    font-size: 30rpx;
    text-align: center;
    margin-bottom: 20rpx;
  }
  .award-condition-column1 {
    flex: 1;
  }
  .award-condition-item {
    height: 70rpx;
    line-height: 70rpx;
  }
  .text {
    margin-top: 20rpx;
    padding: 30rpx 30rpx;
    background-color: #fff;
    textarea {
      width: 100%;
      font-size: 32rpx;
      color: #333;
    }
  }
  .to-vip {
    display: flex;
    justify-content: center;
    margin-top: 50rpx;
    span {
      padding: 14rpx 30rpx;
      border: 2rpx solid #c2a605;
      color: #c2a605;
      font-size: 30rpx;
    }
  }
  .btn-section {
    width: 100%;
    margin-top: 30rpx;
    .btn-inner {
      padding: 20rpx 20rpx;
    }
  }
}
</style>
